package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper,Clazz> implements ClazzService {

//    @Autowired
//    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public void insert(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        save(clazz);
    }


    @Override
    public PageResult pageList(String name, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
//        PageHelper.startPage(page, pageSize);
//
//        List<Clazz> dataList = clazzMapper.list(name,begin,end);
//        Page<Clazz> p = (Page<Clazz>) dataList;

        IPage<Clazz> p=new Page<>(page,pageSize);
        LambdaQueryWrapper<Clazz> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(Clazz::getName,name).between(Clazz::getEndDate,begin,end);
        p=page(p, queryWrapper);
        return new PageResult(p.getTotal(), p.getRecords());
    }


    @Override
    public Clazz getInfo(Integer id) {
        return  getById(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        updateById(clazz);
    }

    @Override
    public void deleteById(Integer id) {
        /*//1. 查询班级下是否有学员
        Integer count = studentMapper.countByClazzId(id);
        if(count > 0){
            throw new BusinessException("班级下有学员, 不能直接删除~");
        }*/
        //2. 如果没有, 再删除班级信息
        deleteById(id);
    }

    @Override
    public List<Clazz> findAll() {
        return list();
    }
}
